package com.campus.schedule.timer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.campus.schedule.entity.Merchant;
import com.campus.schedule.entity.Order;
import com.campus.schedule.service.MerchantService;
import com.campus.schedule.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商户销量统计定时任务
 * 每天凌晨0点20分执行，统计最近30天已完成订单数量并更新到merchant表的sales字段
 *
 * @author System
 * @since 2025-01-22
 */
@Slf4j
@Service
public class MerchantSalesUpdateScheduleService {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private OrderService orderService;

    /**
     * 每天凌晨0点20分执行商户销量统计更新
     */
    @Scheduled(cron = "0 20 0 * * ?")
    public void updateMerchantSales() {
        log.info("开始执行商户销量统计更新任务...");
        
        try {
            // 计算时间范围：最近30天（不包括今天）
            LocalDateTime endTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime startTime = endTime.minusDays(30);
            
            log.info("统计时间范围：{} 至 {}", startTime, endTime);
            
            // 获取所有商户
            List<Merchant> merchants = merchantService.list();
            log.info("共找到 {} 个商户需要更新销量", merchants.size());
            
            int successCount = 0;
            int errorCount = 0;
            
            for (Merchant merchant : merchants) {
                try {
                    // 查询该商户最近30天已完成的订单数量
                    LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Order::getMerchantId, merchant.getId())
                            .eq(Order::getStatus, 4) // 已完成状态
                            .ge(Order::getFinishTime, startTime)
                            .lt(Order::getFinishTime, endTime);
                    
                    long salesCount = orderService.count(queryWrapper);
                    
                    // 更新商户的销量字段
                    LambdaUpdateWrapper<Merchant> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(Merchant::getId, merchant.getId())
                            .set(Merchant::getSales, (int) salesCount);
                    
                    boolean updateResult = merchantService.update(updateWrapper);
                    
                    if (updateResult) {
                        successCount++;
                        log.debug("商户 {} (ID: {}) 销量更新成功，最近30天完成订单数：{}", 
                                merchant.getName(), merchant.getId(), salesCount);
                    } else {
                        errorCount++;
                        log.warn("商户 {} (ID: {}) 销量更新失败", merchant.getName(), merchant.getId());
                    }
                    
                } catch (Exception e) {
                    errorCount++;
                    log.error("更新商户 {} (ID: {}) 销量时发生异常：{}", 
                            merchant.getName(), merchant.getId(), e.getMessage(), e);
                }
            }
            
            log.info("商户销量统计更新任务完成，成功更新：{} 个，失败：{} 个", successCount, errorCount);
            
        } catch (Exception e) {
            log.error("执行商户销量统计更新任务时发生异常：{}", e.getMessage(), e);
        }
    }
}